package com.meshnetics.gb.util.formatters;

import java.nio.ByteBuffer;

/**
 * Base class for byte buffer formatters.
 *
 * @author Yury Aserchev (yaserchev@meshnetics.com)
 *         Date: 27.08.2007 13:09:45
 */
abstract class AbstractByteBufferFormat implements BufferFormatter {
    /**
     * Helper function - return copy of buffer to avoid storing
     * position and other state variables during buffer formatting.
     * <br/><b>Note: </b>Source buffer cannot be readonly !
     * @param byteBuffer source buffer.
     * @return buffer copy.
     * @throws NullPointerException if parameter is null.
     * @throws IllegalArgumentException if paseed buffer is readonly buffer.
     */
    protected final ByteBuffer duplicateBuffer(final ByteBuffer byteBuffer){
        if (byteBuffer == null) {
            throw new NullPointerException("parameter byteBuffer is null");
        }
        if (byteBuffer.isReadOnly()) {
            throw new IllegalArgumentException("Cannot duplicate readonly buffer");
        }
        return ByteBuffer.wrap(byteBuffer.array()).order(byteBuffer.order());
    }
}
